import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../components/HelloWorld.vue'
import Login from '../components/login.vue'
import welcome from '../components/Welcome.vue'
import Users from '../components/user/Users.vue'

Vue.use(VueRouter)

const routes = [
  { path: "/", redirect: "/login " },
  { path: "/login", component: Login },
  {
    path: "/home",
    component: Home,
    redirect: "/welcome",
    children: [
      { path: "/welcome", component: welcome },
      { path: '/users', component: Users }
    ]
  },
]

const router = new VueRouter({
  routes
})

// router.beforeEach导航守卫,守卫是异步解析执行，此时导航在所有守卫 resolve 完之前一直处于 等待中。所有路由都要经过这个函数处理
router.beforeEach((to, from, next) => {
  // to 将要访问的路径
  if (to.path === "/login") return next();
  // 获取token
  const vv = window.sessionStorage.getItem("token");
  //toekn为false 则跳回登录页
  if (!vv) return next("/login");
  next();
});

export default router
